package cn.yangliu.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.imageio.ImageIO;
import javax.net.ssl.SSLContext;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;

/**
 * Created by 杨柳 on 2016/8/5 0005.
 * email:yangliu@buestc.com
 * tel:18523437817
 */
public class CommClient {
    public static final String UTF8 = "UTF-8";
    public static final String GBK = "GBK";
    public static final String GB2312 = "GB2312";

    public static String sendGetRequest(String reqURL, String decodeCharset, Map<String, String> params) {
        return invokeGet(reqURL, decodeCharset, params);
    }

    public static String sendGetRequest(String reqURL) {
        return invokeGet(reqURL, UTF8, null);
    }

    public static String sendGetRequest(String reqURL, Map<String, String> params) {
        return invokeGet(reqURL, UTF8, params);
    }


    public static String sendPostRequest(String reqURL, String decodeCharset, Map<String, String> param) {
        return invokePost(reqURL, decodeCharset, param);
    }

    public static String sendPostRequest(String reqURL, Map<String, String> param) {
        return invokePost(reqURL, UTF8, param);
    }


    /**
     * 多文件 不重名
     *
     * @param reqURL
     * @param files
     * @return
     */
    public static String sendFile1(String reqURL, Map<String, String> files) {
        Set<String> filenames = files.keySet();
        Map<String, File> files_map = new HashMap<>();
        for (String filename : filenames) {
            File file = new File(files.get(filename));
            files_map.put(filename, file);
        }
        return sendFile2(reqURL, files_map);
    }

    /**
     * 多文件 不重名
     *
     * @param reqURL
     * @param files
     * @return
     */
    public static String sendFile2(String reqURL, Map<String, File> files) {
        HttpPost httpPost = new HttpPost(reqURL);
        Set<String> filenames = files.keySet();
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//      builder.setCharset(Charset.forName("uft-8"));//设置请求的编码格式
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式

        for (String filename : filenames) {
            builder.addBinaryBody(filename, files.get(filename));
        }
        HttpEntity entity = builder.build();// 生成 HTTP POST 实体
        httpPost.setEntity(entity);
        return doRequest(reqURL, UTF8, httpPost);
    }

    /**
     * 单个文件
     *
     * @param reqURL
     * @param filename
     * @param pathname
     * @return
     */
    public static String sendFile(String reqURL, String filename, String pathname) {
        List<String> files = Arrays.asList(pathname);
        return sendFile2(reqURL, filename, files);
    }

    /**
     * 多文件 重名
     *
     * @param reqURL
     * @param pathnames
     * @return
     */
    public static String sendFile2(String reqURL, String filename, List<String> pathnames) {
        List<File> files = new ArrayList<>();
        for (String pathname : pathnames) {
            File file = new File(pathname);
            files.add(file);
        }
        return sendFile1(reqURL, filename, files);
    }

    /**
     * 多文件 重名
     *
     * @param reqURL
     * @param files
     * @return
     */
    public static String sendFile1(String reqURL, String filename, List<File> files) {
        HttpPost httpPost = new HttpPost(reqURL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//      builder.setCharset(Charset.forName("uft-8"));//设置请求的编码格式
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式

        for (File file : files) {
            builder.addBinaryBody(filename, file);

        }
        HttpEntity entity = builder.build();// 生成 HTTP POST 实体
        httpPost.setEntity(entity);
        return doRequest(reqURL, UTF8, httpPost);
    }

    /**
     * 上传文件
     *
     * @param reqURL
     * @param filename
     * @param is
     * @return
     */
    public static String sendFile(String reqURL, String filename, InputStream is) {
        HttpPost httpPost = new HttpPost(reqURL);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//      builder.setCharset(Charset.forName("uft-8"));//设置请求的编码格式
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//设置浏览器兼容模式
        builder.addBinaryBody(filename, is);
        HttpEntity entity = builder.build();// 生成 HTTP POST 实体
        httpPost.setEntity(entity);
        return doRequest(reqURL, UTF8, httpPost);
    }

    public static String sendPostRequest(String reqURL) {
        return invokePost(reqURL, UTF8, null);
    }

    private static String invokeGet(String reqURL, String decodeCharset, Map<String, String> params) {
        if (params != null) {
            reqURL = setParams(reqURL, params);
        }
        HttpGet httpGet = new HttpGet(reqURL);
        String responseContent = doRequest(reqURL, decodeCharset, httpGet);
        return responseContent;
    }

    protected static String invokePost(String reqURL, String decodeCharset, Map<String, String> param) {
        HttpPost httpPost = postForm(reqURL, param); // 创建org.apache.http.client.methods.HttpGet
        return doRequest(reqURL, decodeCharset, httpPost);
    }

    protected static String doRequest(String reqURL, String decodeCharset, HttpRequestBase request) {
        if (cookie != null) {
            request.setHeader("cookie", cookie);
        }

        String responseContent = null; // 响应内容
        CloseableHttpClient httpClient = createSSLClientDefault(reqURL); // 创建默认的httpClient实例
       /* if (reqURL.startsWith("https://")) {
            httpClient = wrapClient(httpClient);
        }*/
        try {
            HttpResponse response = httpClient.execute(request); // 执行GET请求
            HttpEntity entity = response.getEntity(); // 获取响应实体
            InputStream is = entity.getContent();
            BufferedImage bi = ImageIO.read(is);

            ImageIO.write(bi, "jpg", new File("E:\\test.jpg"));
            if (null != entity) {
                responseContent = EntityUtils.toString(entity,
                        decodeCharset == null ? "UTF-8" : decodeCharset);
                EntityUtils.consume(entity); // Consume response content
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                httpClient.close(); // 关闭连接,释放资源
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        return responseContent;
    }


    public static void downloadIMG(String reqURL, String pathname, String method) {
        HttpRequestBase request = null;
        if ("post".equalsIgnoreCase(method)) {
            request = new HttpPost(reqURL);
        }
        if ("get".equalsIgnoreCase(method)) {
            request = new HttpGet(reqURL);
        }
        downloadIMG(reqURL, request, pathname);
    }

    public static InputStream getInputStream(String reqURL, String method) {
        HttpRequestBase request = null;
        if ("post".equalsIgnoreCase(method)) {
            request = new HttpPost(reqURL);
        }
        if ("get".equalsIgnoreCase(method)) {
            request = new HttpGet(reqURL);
        }
        return getInputStream(reqURL, request);
    }

    protected static InputStream getInputStream(String reqURL, HttpRequestBase request) {
        if (cookie != null) {
            request.setHeader("cookie", cookie);
        }

        CloseableHttpClient httpClient = createSSLClientDefault(reqURL); // 创建默认的httpClient实例
        try {
            HttpResponse response = httpClient.execute(request); // 执行GET请求
            HttpEntity entity = response.getEntity(); // 获取响应实体
            InputStream is = entity.getContent();
            return is;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            try {
                /*httpClient.close();*/ // 不能关闭 关闭后is不能使用
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    protected static void downloadIMG(String reqURL, HttpRequestBase request, String pathname) {
        try{
            InputStream is = getInputStream(reqURL,request);
            BufferedImage bi = ImageIO.read(is);
            File file = new File(pathname);
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            ImageIO.write(bi, "jpg",file);
        }catch (Exception e){
            throw new RuntimeException(e);
        }

    }


    protected static String setParams(String url, Map<String, String> params) {
        StringBuffer sb = new StringBuffer(url).append("?");
        if (params != null) {
            Set<String> keys = params.keySet();
            for (String key : keys) {
                sb.append(key).append("=").append(params.get(key)).append("&");
            }
        }
        return sb.toString();
    }

    protected static HttpPost postForm(String url, Map<String, String> params) {
        HttpPost httpost = new HttpPost(url);
        if (params != null) {
            List<NameValuePair> nvps = new ArrayList<>();
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                nvps.add(new BasicNameValuePair(key, params.get(key)));
            }
            try {
                httpost.setEntity(new UrlEncodedFormEntity(nvps, UTF8));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return httpost;
    }


    protected static CloseableHttpClient createSSLClientDefault(String url) {
        if (url.startsWith("https://")) {
            try {
                SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                    //信任所有
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
                return HttpClients.custom().setSSLSocketFactory(sslsf).build();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return HttpClients.createDefault();

    }

    private static String cookie = null;

    public static void main(String[] args) {
      /*  cookie = "SESSION=a31889f9-a80e-4401-bca2-aa5042867734";
        Map<String, String> params = new HashMap<>();
        params.put("mobile", "18523437817");
        String content = sendGetRequest("http://39.108.5.249:8080/app/userInfo/sendValidateCode.do", params);
        //正确的
        //            request.setHeader("sign", "C5911E2155DE0FD43BD7C8E59F17D4D6");
        //错误的
        params.put("sign", "C5911E2155DE0FD43BD7C8E59F17D4D");
        //        String content = sendGetRequest("http://127.0.0.1/app/userInfo/sendValidateCode.do",params);
           *//*request.setHeader("os", "os");
        request.setHeader("osVersion", "osVersion");
        request.setHeader("appVersion", "appVersion");
        request.setHeader("timestamp", "timestamp");*//*

        System.out.println(content);
*/

        String url = "http://userportal.bionictech.cn/getCode.html";
        downloadIMG(url,"E:/image/test2.jpg","get");
 /*       fad1856507b4478bbb911701ab97c5b0


        http://route.showapi.com/926-1*/
    }

}
